﻿#region Header
// Copyright (c) 2015 OPEN TONE, Inc.
// Released under the MIT license
// http://opensource.org/licenses/mit-license.php
#endregion
using System;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace OpenXmlLib.Excel.Impl
{
	/// <summary>
	/// Workbook実装
	/// </summary>
	public class WorkbookImpl : IWorkbook
	{
		// WorkbookPartオブジェクト
		private readonly WorkbookPart workbookPart;

		/// <summary>
		/// 
		/// </summary>
		/// <see cref="IWorkbook.SharedStringTable"/>
		public ISharedStringTable SharedStringTable
		{
			get
			{
				var tableParts = workbookPart.GetPartsOfType<SharedStringTablePart>();
				ISharedStringTable table
					= new SharedStringTableImpl(this, tableParts.FirstOrDefault());
				return table;
			}
		}

		/// <summary>
		/// privateコンストラクタ
		/// </summary>
		private WorkbookImpl() { }

		/// <summary>
		/// コンストラクタ
		/// </summary>
		/// <param name="workbookPart">WorkbookPartオブジェクト</param>
		internal WorkbookImpl(WorkbookPart workbookPart)
		{
			this.workbookPart = workbookPart;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sheetName"></param>
		/// <returns></returns>
		/// <see cref="IWorkbook.GetWorksheet"/>
		public IWorksheet GetWorksheet(String sheetName)
		{
			IWorksheet worksheet = null;
			foreach (Sheet s in workbookPart.Workbook.Descendants<Sheet>())
			{
				if (s.Name.ToString().Equals(sheetName, StringComparison.OrdinalIgnoreCase))
				{
					WorksheetPart wsPart = workbookPart.GetPartById(s.Id) as WorksheetPart;
					worksheet = new WorksheetImpl(this, wsPart);
					break;
				}
			}
			return worksheet;
		}
	}
}
